<?php

namespace app\admin\controller\dymz;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Cache;

/**
 * 资源上传
 *
 * @icon fa fa-circle-o
 */
class Script extends Backend
{

    /**
     * Script模型对象
     * @var \app\admin\model\dymz\Script
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dymz\Script;
        $this->view->assign("serialStatusList", $this->model->getSerialStatusList());
        $this->view->assign("operateStatusList", $this->model->getOperateStatusList());
        $this->view->assign("tagListList", $this->model->getTagListList());
        $this->view->assign("qualificationList", $this->model->getQualificationList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $url = 'https://open.douyin.com/api/playlet/v2/video/create/';

        $cover_list = explode(",",$params['cover_list']);
        $tag = array();
        foreach($params['tag_list'] as $item){
            $tag[] = intval($item);
        }
        $main_content = array(
            "title" => $params['title'],
            "seq_num" => intval($params['seq_num']),
            "cover_list" => $cover_list,
            "year" => intval($params['year']),
            "album_status" => intval($params['serial_status']),
            "recommendation" => $params['recommendation'],
            "desp" => $params['description'],
            "tag_list" => $tag,
            "qualification" => intval($params['qualification']),
            "record_audit_info" => '',
        );
        $data = array(
            "ma_app_id" => 'tte3e2955f7cd2a7d301',
            "album_info" => $main_content,
            "access_token" => $this->get_dy_access_token()
        );
        
        $json_res = $this->json_token_post($url,$data);
        $res = json_decode($json_res,true);
        if($res['err_no'] == '28001008'){
            $data = array(
                "ma_app_id" => 'tte3e2955f7cd2a7d301',
                "album_info" => $main_content,
                "access_token" => $this->get_dy_access_token()
            );
            $json_res = $this->json_token_post($url,$data);
            $res = json_decode($json_res,true);
        }
        if($res['err_no'] != "0"){
            $this->error($res['err_msg']);
        }
        $params['album_id'] = $res['data']['album_id'];
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

     //获取小程序二维码的token
     public function get_dy_access_token()
     {
         //先判断缓存里面的access_token过期了没有
         if(Cache::get('dy_access_token')){
             //没过期直接拿出来用
             $a = Cache::get('dy_access_token');
             return $a;
         }else{
            //过期了就重新获取
             $client_key = 'tte3e2955f7cd2a7d301';
             $client_secret = '1a8c380ad5fa5b6e3d0455604c47eecf34ba2038';
             $grant_type = 'client_credential';
             $url = "https://open-sandbox.douyin.com/oauth/client_token/";
             $data = array(
                 "client_key" => $client_key,
                 "client_secret" => $client_secret,
                 "grant_type" => $grant_type,
             );
             //请求接口，获取accesstoken
             $user_obj = json_decode($this->get_dy_client_token($url,$data),true);
             // print_r($user_obj['data']);exit;
             //然后将accesstoken存入缓存里面，官方过期时间7200秒，缓存里面可以过期的早一点，自己把控
             Cache::set('dy_access_token',$user_obj['data']['access_token'],900);
             return Cache::get('dy_access_token');
         }
     }
     //获取抖音小程序二维码的token
     public function get_new_dy_access_token()
     {
         //过期了就重新获取
         $client_key = 'tte3e2955f7cd2a7d301';
         $client_secret = '1a8c380ad5fa5b6e3d0455604c47eecf34ba2038';
         $grant_type = 'client_credential';
         $url = "https://open-sandbox.douyin.com/oauth/client_token/";
         $data = array(
             "client_key" => $client_key,
             "client_secret" => $client_secret,
             "grant_type" => $grant_type,
         );
         //请求接口，获取accesstoken
         $user_obj = json_decode($this->get_dy_client_token($url,$data),true);
         //然后将accesstoken存入缓存里面，官方过期时间7200秒，缓存里面可以过期的早一点，自己把控
         Cache::set('dy_access_token',$user_obj['access_token'],900);
 
         return Cache::get('dy_access_token');
     }
 
     /**
      * 发送post请求
      */
     function get_dy_client_token($url, $data = [])
     {
         //$data=http_build_query($data);
         //$data=json_encode($data);
         $curl = curl_init();
 
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
         if(!$data){
             return 'data is null';
         }
         if(is_array($data))
         {
             $data = json_encode($data);
         }
         curl_setopt($curl, CURLOPT_POST, 1);
         curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
         curl_setopt($curl, CURLOPT_HEADER, 0);
         curl_setopt($curl, CURLOPT_HTTPHEADER,array(
             'Content-Type: application/json',
         ));
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         $res = curl_exec($curl);
         $errorno = curl_errno($curl);
         if ($errorno) {
             return $errorno;
         }
         curl_close($curl);
         return $res;
 
     }

     /**
     * 发送post请求
     */
    function json_token_post($url, $data = [])
    {
        //$data=http_build_query($data);
        //$data=json_encode($data);
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $access_token = $data['access_token'];
        unset($data['access_token']);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json',
            'access-token: '.$access_token,
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function getStatus($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $script = DB::name("dymz_script")->where("id",$ids)->find();
        $url = 'https://open.douyin.com/api/playlet/v2/album/fetch/';
        $data = array(
            "ma_app_id" => 'tte3e2955f7cd2a7d301',
            "resource_id" => $script['resource_id'],
            "version" => $script['version'],
            "access_token" => $this->get_dy_access_token()
        );
        $json_res = $this->json_token_post($url,$data);
        $res = json_decode($json_res,true);
        if($res['err_no'] == '28001008'){
            $data = array(
                "resource_id" => $script['resource_id'],
                "version" => $script['version'],
                "access_token" => $this->get_new_dy_access_token()
            );
            $json_res = $this->json_token_post($url,$data);
            $res = json_decode($json_res,true);
        }
        $params['status'] = $res['data']['audit_status'];
        $params['id'] = $ids;
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

     /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function getShangPage()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
}
